package com.nageffer.shortlink.project.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nageffer.shortlink.project.common.convention.exception.ServiceException;
import com.nageffer.shortlink.project.dto.biz.ShortLinkStatsRecordDTO;
import com.nageffer.shortlink.project.mq.idempotent.MessageQueueIdempotentHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class RabbitMqStatsConsumer {

    private final ShortLinkStatsSaveConsumer shortLinkStatsSaveConsumer;

    private final MessageQueueIdempotentHandler messageQueueIdempotentHandler;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "shortLink.queue", durable = "true"),
            exchange = @Exchange(name = "shortLink.exchange", type = ExchangeTypes.DIRECT),
            key = {"shortLink"}
    ))
    public void rabbitMqListener(Message message){
        //获取消息id
        String messageId = message.getMessageProperties().getMessageId();

        //获取消息本身，并转换成map
        byte[] body = message.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> producerMap = null;
        try {
            producerMap = objectMapper.readValue(body, Map.class);
        } catch (IOException e) {
            throw new ServiceException("消息处理错误！");
        }

        if (!messageQueueIdempotentHandler.isMessageProcessed(messageId)) {
            if (messageQueueIdempotentHandler.isAccomplish(messageId)) {
                return;
            }
            throw new ServiceException("消息未完成流程，需要消息队列重试");
        }

        try {
            String fullShortUrl = producerMap.get("fullShortUrl");
            String gid = producerMap.get("gid");
            ShortLinkStatsRecordDTO statsRecord = JSON.parseObject(producerMap.get("statsRecord"), ShortLinkStatsRecordDTO.class);
            //处理消息
            shortLinkStatsSaveConsumer.actualSaveShortLinkStats(fullShortUrl, gid, statsRecord);
        } catch (Throwable ex) {
            messageQueueIdempotentHandler.delMessageProcessed(messageId);
            log.error("记录短链接监控消费异常", ex);
            throw new ServiceException("处理消息失败！");
        }
        //设置消息为完成状态
        messageQueueIdempotentHandler.setAccomplish(messageId);
    }

}
